﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Msdn5.Framework
{
    /// <summary>
    /// 对于数字类型的常用转换
    /// </summary>
    public static class NumHelper
    {
        /// <summary>
        /// 尝试转换为int
        /// </summary>
        /// <param name="object">任意对象</param>
        /// <returns>int值</returns>
        public static int TryToInt(this object o)
        {
            if (o == null) { return 0; }
            int val = 0;
            if (int.TryParse(o.ToString(), out val))
            {
                return val;
            }
            return val;
        }
        /// <summary>
        /// 四舍五入转高精度小数
        /// </summary>
        /// <param name="d">需要转换的值</param>
        /// <param name="dec">保留小数位,默认为2</param>
        /// <returns>转换后的值</returns>
        public static decimal Round(this decimal d, int dec = 2)
        {
            return Math.Round(d, dec, MidpointRounding.AwayFromZero);
        }
        /// <summary>
        /// 四舍五入转双精度小数
        /// </summary>
        /// <param name="d">需要转换的值</param>
        /// <param name="dec">保留小数位,默认为2</param>
        /// <returns>转换后的值</returns>
        public static double Round(this double d, int dec = 2)
        {
            return Math.Round(d, dec, MidpointRounding.AwayFromZero);
        }

        /// <summary>
        /// 尝试转换为bool
        /// 不存在直接为false
        /// 存在则尝试转换
        /// </summary>
        /// <param name="key">任意对象</param>
        /// <returns>bool值</returns>
        public static bool TryToBool(this object key)
        {
            bool result;
            bool.TryParse(key?.ToString(), out result);
            return result;
        }

    }
}
